﻿using SolidWorks.Interop.sldworks;
using SwParaPlatform2.tools;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SwParaPlatform2.dlgRuleConfig
{
    public partial class dlgSelectDrw: Form
    {
        public dlgSelectDrw()
        {
            InitializeComponent();
            InitList();
        }

        private void InitList() {
            ISldWorks swApp = SwAppMgr.Instance.iSwApp;
            // 获取单例对象
            DrawingManager manager = DrawingManager.GetInstance(swApp);
            // 获取所有待打开的工程图文件路径
            List<string> drawingFiles = manager.GetDrawingFiles();
            List<string> dAllRuleConfigData = RuleConfigModel.Instance.GetSelectDrwList();

            for (int i = 0; i < drawingFiles.Count; i++)
            {
                string fileName = Path.GetFileName(drawingFiles[i]);
                checkedListBox1.Items.Add(drawingFiles[i], dAllRuleConfigData.Contains(fileName));
            }
            AdjustFormWidth();
        }

        private List<string> GetCheckedItems()
        {
            List<string> selectedItems = new List<string>();

            foreach (var item in checkedListBox1.CheckedItems)
            {
                string fullPath = item.ToString();
                selectedItems.Add(Path.GetFileName(fullPath));
            }
            return selectedItems;
        }

        private void AdjustFormWidth()
        {
            int maxWidth = 0;
            using (Graphics g = checkedListBox1.CreateGraphics())
            {
                foreach (var item in checkedListBox1.Items)
                {
                    // 计算每个元素的像素宽度
                    int itemWidth = (int)g.MeasureString(item.ToString(), checkedListBox1.Font).Width;
                    maxWidth = Math.Max(maxWidth, itemWidth);
                }
            }

            // 添加一些边距和复选框宽度
            int padding = 40;
            int newWidth = maxWidth + padding;

            // 设置窗体和CheckedListBox宽度
            this.Width = Math.Max(newWidth, this.MinimumSize.Width);
            checkedListBox1.Width = this.ClientSize.Width;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            RuleConfigModel.Instance.SetSelectDrwList(GetCheckedItems());
            this.Close();
        }
    }
}
